<?php

class AddressController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';
	public $model;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','dynamicCities','dynamicAreas'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Address;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
	
		if(isset($_POST['Address']))
		{
			$model->attributes=$_POST['Address'];
			$user_id = Yii::app()->user->id;
			$user = User::model()->findByPk($user_id);
			$order = new Orders;
			$time = time();
			$sn = 'sn'.date('YmdHis').$user_id;
			$order->order_sn = $sn;
			$order->user_id = $user_id;
			$order->order_status = 1;
			$order->country = $model->country;
			$order->province = $model->province;
			$order->city = $model->city;
			$order->district = $model->district;
			$order->address = $model->address;
			$order->zipcode = $model->zipcode;
			$order->name = $model->name;
			$order->telephone = $model->telephone;
			$order->order_time = $time;
			$order->pay_time = 0;
			$order->total = 0;
			$order->save();
			$discount = 1.0;
			if(((int)$user->scores)>500 && ((int)$user->scores)<=1000){
				$discount = $discount * 0.95;
			
			}elseif(((int)$user->scores)>1000){
				$discount = $discount * 0.9;
			}
			$order_id = Orders::model()->find(
			array(
			'condition'=>'order_sn=:order_sn',
			'params'=>array(':order_sn'=>$sn) 
			))->order_id;
			$carts =Cart::model()->findAllBySql('select * from es_cart where user_id = '.$user_id);
			foreach ($carts as $cart){
				$orderList = new OrderList();
				$orderList->goods_id = $cart->goods_id;
				$goods = Goods::model()->findByPk($cart->goods_id);
				$orderList->goods_name = $cart->good_name;
				$orderList->order_id = $order_id;
				$orderList->price = $cart->price;
				$orderList->subtotal = $cart->subtotal;
				$orderList->quantity = $cart->quantity;
				$orderList->discount = $goods->goods_discount*$discount;
				//echo $orderList->discount;
				//Yii::app()->end();
				$orderList->save();
				$order->total = $order->total + $cart->subtotal;
				$cart->delete();
			}
			$order->order_status = 1;
			$order->update();
			/**
			$user = User::model()->findByPk($user_id);
			if($user->balance>$order->total){
				$user->balance = $user->balance - $order->total;
				$user->consumption =  $user->consumption + $order->total;
				$user->scores =  $user->scores + (int)($order->total);
				$order->pay_status = 1;
				$user->update();
			}
			$order->order_status = 2;
			$order->update();*/	
			$this->redirect(array("orders/view",'id'=>$order_id));	
		}
		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Address']))
		{
			$model->attributes=$_POST['Address'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->default_address_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Address');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Address('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Address']))
			$model->attributes=$_GET['Address'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Address::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='address-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	/**
	 * add the dynamic doropDownList for city
	 */
	public function actionDynamicCities()
	{
		$data=Region::model()->findAll('parent_id=:parent_id', 
			array(':parent_id'=>(int) $_POST['province']));

		$data=CHtml::listData($data,'region_id','region_name');
		foreach($data as $value=>$name)
		{
			echo CHtml::tag('option',
				array('value'=>$value),CHtml::encode($name),true);
		}	
	}
	
	/**
	 * update the dynamic dropdownList for district
	 */
	public function actionDynamicAreas()
	{
	
		$data=Region::model()->findAll('parent_id=:parent_id', 
			array(':parent_id'=>(int) $_POST['city']));

		$data=CHtml::listData($data,'region_id','region_name');
		foreach($data as $value=>$name)
		{
			echo CHtml::tag('option',
				array('value'=>$value),CHtml::encode($name),true);
		}
	}
}
